/** dute.ui.js **/
!function (n) {
  "use strict";

  var ux = {
    extend: function (params) {
      for (var o in params) {
        this[o] = params[o];
      }
    },
    /**
     * 请求数据
     * action:接口标识
     * data:请求数据
     * callback:返回值回调(protocol)
     * toast:protocol中的message是否托管显示
     */
    request: function (action, params, callback, toast, loadding, autoLogin) {
      if (action.indexOf("{{") == 0) return;
      var THIS = this;
      var data = { method: action, params: JSON.stringify(params) };
      //自动添加TOKEN参数
      data.token = localStorage.getItem('token') || "";
      data.timestamp = this.formatTime(new Date());
      data.appid = config.appid;
      data.lat = "";
      data.lng = "";
      data.sign = this.getSign(config.secret, data);

      if (config.debug) {
        console.log(config.apiUrl, JSON.stringify(data));
      }

      if (("" + loadding) != "false") {
        ux.loading("正在加载数据");
      }
      //console.log(">>",config.apiUrl,JSON.stringify(data));
      window._request = {
        action: action, params: params, callback: callback, toast: toast, loadding: loadding, autoLogin: autoLogin
      };
      ux.ajax({
        url: config.apiUrl,
        data: data,
        dataType: 'json',//服务器返回json格式数据
        header: { 'Content-Type': 'application/json' },
        timeout: 10000,
        cache:false,
        success: function (protocol) {
          if(ux.getProtocol){
        	  protocol = ux.getProtocol(protocol);
          }
          if (("" + loadding) != "false") {
            ux.loading(false);
          }
          if (config.debug) {
        	  console.log("返回:"+JSON.stringify(protocol));
          }

          var errorCodes = {
            invalid_param: "数据请求异常(001)，请重试",
            invalid_timestamp: "数据请求异常(002)，请重试",
            invalid_client: "数据请求异常(003)，请重试",
            invalid_sign: "数据请求异常(004)，请重试",
            invalid_method: "数据请求异常(005)，请重试",
            class_not_found: "数据请求异常(006)，请重试",
            class_supper_error: "数据请求异常(007)，请重试",
            invalid_token: "未登录或登录已失效",
            user_token_error: "未登录或登录已失效",
            login_by_other: "你的帐号已在其它设备登录",
            method_not_found: "数据请求异常(009)，请重试",
            return_type_error: "数据请求异常(010)，请重试",
            return_value_null: "数据请求异常(011)，请重试",
            system_error_exception: "数据请求异常(012)，请重试"
          };

          //如果要求显示信息提示
          if (toast && protocol.message) {
            if (protocol.error && errorCodes[protocol.error]) {
              ux.toast(errorCodes[protocol.error]);
              console.log(protocol.message);
            } else {
              ux.toast(protocol.message);
            }
          }

          if (protocol.success) {
            if (protocol.data && protocol.list) {
              protocol.data.list = protocol.list;
            }
            if (protocol.pageInfo || protocol.data.pageInfo) {
              var pageInfo = (protocol.pageInfo || protocol.data.pageInfo);
              if (!window._pageInfo || window._pageInfo.index < pageInfo.index) {
                window._pageInfo = pageInfo;
                if (window._list && protocol.data.list) {
                  var newList = [];
                  for (var o in window._list) {
                    newList.push(window._list[o]);
                  }
                  for (var o in protocol.data.list) {
                    newList.push(protocol.data.list[o]);
                  }
                  var more100 = newList.length - 100;
                  for (var i = 0; i < more100; i++) {
                    newList.unshift();
                  }
                  protocol.data.list = newList;
                  protocol.list = newList;
                }
              }
            }
            if (protocol.data.list) {
              window._list = protocol.data.list;
            }
            callback(protocol);
          } else {//网络请求异常
            //如果返回错误代码为invalid_token，表示需要登录
            if (("" + autoLogin) != "false" && (protocol.error == "invalid_token" || protocol.error == "user_token_error")) {
              ux.navigateTo(config.loginPage);
              ux.toast("未登录或登录已失效");
            } else if ("login_by_other" == protocol.error) {
              localStorage.removeItem("token");
              ux.toast("你的帐号已在其它设备登录");
              callback(protocol);
            } else {
              callback(protocol);
            }
          }
        },
        error: function (res, type) {
          if (("" + loadding) != "false") {
            ux.loading(false);
          }
          var errorCodes = {
            "timeout": "网络请求超时",
            "error": "网络错误",
            "abort": "网络未连接",
            "parsererror": "网络解析出错"
          };
          if (type && errorCodes[type]) {
            ux.toast(errorCodes[type]);
          }
        }
      });
    },
    /**
     * 获取参数签名
     */
    getSign: function (secrent, data) {
      var strSign = secrent + "appid" + data.appid;
      if (typeof (data.lat) != "undefined" && typeof (data.lng) != "undefined") {
        strSign += "lat" + data.lat + "lng" + data.lng;
      }
      strSign += "method" + data.method + "params" + data.params + "timestamp" + data.timestamp + "token" + data.token + secrent;
      return md5(strSign).toUpperCase();
    },
    bin2hex: function (str) {
      var result = "";
      for (i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        result += byte2Hex(c >> 8 & 0xff); // 高字节
        result += byte2Hex(c & 0xff);	// 低字节
      }
      return result;
    },
    byte2Hex: function (b) {
      if (b < 0x10)
        return "0" + b.toString(16);
      else
        return b.toString(16);
    },

    /**
     * 格式化时间
     */
    formatTime: function (date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
    },
    formatNumber: function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    date: function (date, strFormat) {
      if (!date) return "";
      var dDate = null;
      if (typeof (date) == "string") {//字符转日期			
        if (strFormat == null) strFormat = 'yyyy-MM-dd hh:mm:ss';
        var compare = { 'y+': 'y', 'M+': 'M', 'd+': 'd', 'H+': 'H', 'm+': 'm', 's+': 's' };
        var result = { 'y': '', 'M': '', 'd': '', 'H': '00', 'm': '00', 's': '00' };
        var tmp = strFormat;
        try {
          for (var k in compare) {
            if (new RegExp('(' + k + ')').test(strFormat))
              result[compare[k]] = date.substring(tmp.indexOf(RegExp.$1), tmp.indexOf(RegExp.$1) + RegExp.$1.length);
          }
        } catch (ex) {
          ux.toast(ex.message);
        }
        dDate = new Date(result['y'], result['M'] - 1, result['d'], result['H'], result['m'], result['s']);
        return dDate;
      } else if (typeof (date) == "number") {
        dDate = new Date(date);
      } else {
        dDate = date;
      }

      var str = strFormat || "yyyy-MM-dd HH:mm:ss";
      var Week = ['日', '一', '二', '三', '四', '五', '六'];

      str = str.replace(/yyyy|YYYY/, dDate.getFullYear());
      str = str.replace(/yy|YY/, (dDate.getYear() % 100) > 9 ? (dDate.getYear() % 100).toString() : '0' + (dDate.getYear() % 100));

      str = str.replace(/MM/, dDate.getMonth() > 8 ? (dDate.getMonth() + 1) : '0' + (dDate.getMonth() + 1));
      str = str.replace(/M/g, dDate.getMonth() + 1);

      str = str.replace(/w|W/g, Week[dDate.getDay()]);

      str = str.replace(/dd|DD/, dDate.getDate() > 9 ? dDate.getDate().toString() : '0' + dDate.getDate());
      str = str.replace(/d|D/g, dDate.getDate());

      str = str.replace(/hh|HH/, dDate.getHours() > 9 ? dDate.getHours().toString() : '0' + dDate.getHours());
      str = str.replace(/h|H/g, dDate.getHours());
      str = str.replace(/mm/, dDate.getMinutes() > 9 ? dDate.getMinutes().toString() : '0' + dDate.getMinutes());
      str = str.replace(/m/g, dDate.getMinutes());

      str = str.replace(/ss|SS/, dDate.getSeconds() > 9 ? dDate.getSeconds().toString() : '0' + dDate.getSeconds());
      str = str.replace(/s|S/g, dDate.getSeconds());

      return str;
    }
  }

  "function" == typeof define && define.amd ? define(function () {
    return ux
  }) : "object" == typeof module && module.exports ? module.exports = ux : n.ux = ux
}(this);